package org.example.shoppingmall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.shoppingmall.entity.Category;
import org.example.shoppingmall.entity.Goods;
import org.example.shoppingmall.service.OpenService;
import org.example.shoppingmall.service.impl.OpenServiceImpl;
import org.example.shoppingmall.util.JsonUtils;
import org.example.shoppingmall.util.ResponseUtil;

import java.io.IOException;
import java.util.List;

@WebServlet("/goods/*")
public class OpenController extends HttpServlet {
    OpenService openService = new OpenServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        switch (uri) {
            case "/goods/display" -> {
                doGoodsDisplay(req,resp);
            }
            case"/goods/category/all" -> {
                doGetAllCategory(req,resp);
            }
            case"/goods/goodsDisplayByCategory" -> {
                doGoodsDisplayByCategory(req,resp);
            }
            case"/goods/goodsSearchByKeyword" -> {
                doGoodsSearchByKeyword(req,resp);
            }
            default -> {

            }
        }
    }


    /**
     * 商品展示
     *
     * @param req  HttpServletRequest 对象
     * @param resp HttpServletResponse 对象
     * @throws IOException 如果响应发送失败
     */

    private void doGoodsDisplay(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = JsonUtils.getJson(req);
        List<Goods> goodsList = null;
        Integer count;
        Integer page_size = json.getInteger("page_size");
        Integer page = json.getInteger("page");
        try {
            // 调用服务获取商品列表
            goodsList = openService.goodsDisplay(page_size,page);
            count = openService.goodsCount();
            // 检查商品列表是否为空，并给出相应的响应
            if (goodsList == null || goodsList.isEmpty() || count==null) {
                // 商品列表为空时，可以返回一个空列表的JSON或特定的错误消息
                ResponseUtil.gen404Response(resp, "没有找到商品");
            } else {
                // 商品列表不为空时，将列表转换为LIST字符串并返回
//                String list = JSON.toJSONString(goodsList);
                ResponseUtil.genCountAndListResponce(resp,"商品列表及总数返回成功",count,goodsList);
            }
        } catch (Exception e) {
            // 处理可能发生的异常，例如服务调用失败
            e.printStackTrace(); // 在实际部署中，应避免直接打印堆栈跟踪到控制台
            ResponseUtil.gen500Response(resp, "获取商品列表失败");
        }
    }

    /**
     * 获取所有类别
     * @param req
     * @param resp
     */
    private void doGetAllCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Category> list = null;
        try {
            list = openService.getAllCategory();
            if (list == null || list.isEmpty()) {
                ResponseUtil.gen404Response(resp, "没有找到类别");
            } else {
                ResponseUtil.genSuccessResponse(resp,"类别列表返回成功",list);
            }
        } catch (Exception e) {
            // 处理可能发生的异常，例如服务调用失败
            e.printStackTrace();
            ResponseUtil.gen500Response(resp, "获取类别列表失败");
        }
    }

    /**
     * 根据类别展示商品
     * @param req
     * @param resp
     * @throws IOException
     */
    private void doGoodsDisplayByCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = JsonUtils.getJson(req);
        Integer category_id = json.getInteger("category_id");
        Integer page_size = json.getInteger("page_size");
        Integer page = json.getInteger("page");
        Integer count;
        List<Goods> list= null;
        try {
            count = openService.goodsCountByCategory(category_id);
            list = openService.goodsDisplayByCategory(category_id,page_size,page);
            if (list == null || list.isEmpty()) {
                ResponseUtil.gen404Response(resp, "没有找到商品");
            } else {
                ResponseUtil.genCountAndListResponce(resp,"商品列表及总数返回成功",count,list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.gen500Response(resp, "获取商品列表失败");
        }
    }

    /**
     * 根据关键字查找商品
     * @param req
     * @param resp
     * @throws IOException
     */
    private void doGoodsSearchByKeyword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = JsonUtils.getJson(req);
        String keyword = json.getString("keyword");
        Integer page_size = json.getInteger("page_size");
        Integer page = json.getInteger("page");
        Integer count;
        List<Goods> list= null;
        try {
            count = openService.goodsCountByKeyword(keyword);
            list = openService.goodsSearchByKeyword(keyword,page_size,page);
            if (list == null || list.isEmpty()) {
                ResponseUtil.gen404Response(resp, "没有找到商品");
            } else {
                ResponseUtil.genCountAndListResponce(resp,"商品列表及总数返回成功",count,list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.gen500Response(resp, "获取商品列表失败");
        }
    }
}
